{% extends "teacher/base.html" %}

{% block title %}成绩趋势分析 - 期末成绩登记统计分析系统{% endblock %}

{% block content %}
<div class="card mt-4">
  <div class="card-title">
    <i class="fas fa-chart-line"></i>
    成绩趋势分析
    <div class="float-end">
      <button class="btn btn-sm btn-outline-primary" onclick="toggleView()">
        <i class="fas fa-exchange-alt"></i> 切换视图
      </button>
    </div>
  </div>
  <div id="chartView" class="chart-container" style="position: relative; height:400px;">
    <canvas id="gradeTrendChart"></canvas>
  </div>
  <div id="tableView" class="table-container" style="display: none;">
    <table class="table table-striped">
      <thead>
        <tr>
          <th class="text-center">学期</th>
          <th class="text-center">平均成绩</th>
        </tr>
      </thead>
      <tbody id="trendTableBody">
      </tbody>
    </table>
  </div>
  <div class="trend-note mt-3">
    <p class="text-muted">
      <i class="fas fa-info-circle"></i>
      成绩趋势分析展示了学生成绩随时间的变化情况，可以帮助教师了解教学效果的变化趋势。
    </p>
  </div>
</div>
{% endblock %}

{% block styles %}
{{ super() }}
<link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
<style>
  .chart-container {
    margin-top: 20px;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }

  .table-container {
    margin-top: 20px;
    background: white;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }

  .card {
    border: none;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border-radius: 15px;
  }

  .card-title {
    padding: 20px;
    background: #e9eef4;
    color: #2c3e50;
    border-radius: 15px 15px 0 0;
    font-size: 1.2em;
  }

  .btn-outline-primary {
    border-color: #2c3e50;
    color: #2c3e50;
  }

  .btn-outline-primary:hover {
    background-color: white;
    color: #764ba2;
  }

  .main-content {
    margin-top: 70px !important;
  }

  .float-end {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-left: auto;
  }

  .trend-note {
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
    font-size: 0.9em;
    margin: 20px;
  }

  .trend-note i {
    color: #6c757d;
    margin-right: 5px;
  }
</style>
{% endblock %}

{% block scripts %}
{{ super() }}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<script>
  let chart = null;
  let trendData = null;

  // 检查Chart.js是否加载成功
  function checkChartJsLoaded() {
    if (typeof Chart === 'undefined') {
      console.error('Chart.js 未加载成功');
      alert('图表库加载失败，请刷新页面重试');
      return false;
    }
    return true;
  }

  function toggleView(event) {
    if (event) {
      event.stopPropagation();
      event.preventDefault();
    }
    const chartView = document.getElementById('chartView');
    const tableView = document.getElementById('tableView');

    if (chartView.style.display !== 'none') {
      chartView.style.display = 'none';
      tableView.style.display = 'block';
      updateTable();
    } else {
      chartView.style.display = 'block';
      tableView.style.display = 'none';
    }

    // 确保analysis-submenu保持展开状态
    const analysisSubmenu = document.querySelector('.analysis-submenu');
    if (analysisSubmenu) {
      analysisSubmenu.classList.add('show');
      const parentCollapse = analysisSubmenu.closest('.collapse');
      if (parentCollapse) {
        parentCollapse.classList.add('show');
      }
    }
  }

  function updateTable() {
    if (!trendData) return;

    const tbody = document.getElementById('trendTableBody');
    tbody.innerHTML = '';

    trendData.labels.forEach((label, index) => {
      const row = document.createElement('tr');
      row.innerHTML = `
        <td class="text-center">${label}</td>
        <td class="text-center">${trendData.values[index]}</td>
      `;
      tbody.appendChild(row);
    });
  }

  document.addEventListener('DOMContentLoaded', function () {
    if (!checkChartJsLoaded()) return;

    fetch('/teacher/analysis/data')
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then(result => {
        if (result.success) {
          trendData = result.data.trend;

          // 创建图表
          const ctx = document.getElementById('gradeTrendChart').getContext('2d');
          if (chart) {
            chart.destroy();
          }
          chart = new Chart(ctx, {
            type: 'line',
            data: {
              labels: trendData.labels,
              datasets: [{
                label: '平均分',
                data: trendData.values,
                borderColor: 'rgba(75, 192, 192, 1)',
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                borderWidth: 2,
                fill: false,
                tension: 0.4
              }]
            },
            options: {
              responsive: true,
              maintainAspectRatio: false,
              plugins: {
                title: {
                  display: true,
                  text: '成绩趋势分析',
                  font: {
                    size: 18,
                    weight: 'bold'
                  },
                  padding: {
                    top: 10,
                    bottom: 20
                  }
                },
                legend: {
                  display: false
                }
              },
              scales: {
                y: {
                  min: 30,
                  max: 100,
                  title: {
                    display: true,
                    text: '平均分'
                  },
                  ticks: {
                    stepSize: 5
                  }
                }
              }
            }
          });
        } else {
          throw new Error(result.message || '获取数据失败');
        }
      })
      .catch(error => {
        console.error('Error:', error);
        const chartView = document.getElementById('chartView');
        chartView.innerHTML = `<div class="text-center p-5 text-danger"><i class="fas fa-exclamation-circle"></i> ${error.message || '获取数据失败，请稍后重试'}</div>`;
      });
  });
</script>
{% endblock %}